package com.LeeCode;

/**
 * 变长子数组求和
 */

public class Code3427 {
    public static void main(String[] args) {
        int[] nums = {2, 3, 1};
        System.out.println(new Code3427().subarraySum(nums));
    }

    public int subarraySum(int[] nums) {
        int sum = 0, n = nums.length;
        int[] preSum = new int[n + 1];
        for (int i = 0; i < n; i++) {
            preSum[i + 1] = preSum[i] + nums[i];
        }
        for (int i = 0; i < n; i++) {
            int start = Math.max(0, i - nums[i]);
            sum += preSum[i + 1] - preSum[start];
        }
        return sum;
    }
}
